//
// StoreNuke.Net -  http://www.storenuke.net
// Copyright (c) 2005
// by Robert J Collins ( info@storenuke.net ) of WillowTree Software, Inc. ( http://www.willowtreesoftware.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace StoreNuke.StarterKit.Commerce.StoreControls
{
	/// <summary>
	///		Summary description for ProductList.
	/// </summary>
	public class ProductList : StoreControl
	{
		protected DataList MyList;
		StoreControlsDB store = new StoreControlsDB();
		protected System.Web.UI.WebControls.Label lblError;
		protected System.Web.UI.WebControls.Label ModelName;
		protected System.Web.UI.WebControls.HyperLink btnPrevTop;
		protected System.Web.UI.WebControls.HyperLink btnNextTop;
		protected System.Web.UI.HtmlControls.HtmlTableCell tblCountTop;
		protected System.Web.UI.WebControls.HyperLink btnPrev;
		protected System.Web.UI.WebControls.HyperLink btnNext;
		protected System.Web.UI.HtmlControls.HtmlTableCell tblCount;
		protected ProductsDB product = new ProductsDB(); 

		private void Page_Load(object sender, EventArgs e)
		{
			if(!Page.IsPostBack)
			{
				Hashtable settings = store.GetStoreControlSettings(StoreControlID);
				if((settings["PageTitle"] != null) && (settings["PageTitle"].ToString()) != "")
				{
					ControlTitle = settings["PageTitle"].ToString();
				}
				else
				{
					try
					{
						ModelName.Text = product.GetSingleProductCategoryDescription(Convert.ToInt32(Request.QueryString["CategoryID"]));
					}
					catch 
					{
						ModelName.Text = "Error Loading Selected Category Information";
					}
				}
			}

			BindDataList();
		}

		private void BindDataList()
		{
			// Obtain products and databind to an asp:datalist control
			ProductsDB productCatalogue = new ProductsDB();
	
			if(Request.Params["txtSearch"] != null)
			{
				BindData(productCatalogue.SearchProductDescriptions(Request.Params["txtSearch"]));
				ControlTitle = "Search Results";

				// Display a message if no results are found
				if (MyList.Items.Count == 0) 
				{
					lblError.Text = "No items matched your query.";
				}
			}
			else
			{
				// Obtain categoryId from QueryString
				int categoryId = Int32.Parse(Request.Params["CategoryID"]);
				BindData(productCatalogue.GetProducts(categoryId, false));
			}
		}

		private void BindData(SqlDataReader dr)
		{
			DataTable dt = new DataTable();

			//Get current paging number
			if (Request.QueryString["PageNumber"] != null)
			{ 
				ViewState["CurrentPage"] = Request.QueryString["PageNumber"]; 
			} 
			else
			{
				ViewState["CurrentPage"] = 1; 
			}

			//Get starting recored (row) number/possition
			int startRecord = (int.Parse(ViewState["CurrentPage"].ToString()) - 1) * Convert.ToInt32(ConfigurationSettings.AppSettings["PageCount"]); 

			//Get the set paging count number (number of products that show at a time)
			int PageSize = Convert.ToInt32(ConfigurationSettings.AppSettings["PageCount"]);

			//Send the datareader and start/end record info and get a dataTable back
			dt = ConvertDataReaderToDataTable2(dr,(startRecord > 0 ? (startRecord + 1) : startRecord),(startRecord > 0 ? (PageSize + startRecord) : PageSize));

			//Bind dataTable
			MyList.DataSource = dt; 
			MyList.DataBind(); 

			//Call paging method
			BuildPagersLinks();
		}

		public DataTable ConvertDataReaderToDataTable2(IDataReader reader, int startPossition, int endPossition) 
		{ 
			//This method excepts a DataReader and a start/end record number and returns a dataTable 
			//with just the required items
			DataTable objDataTable = new DataTable(); 
			int intFieldCount = reader.FieldCount; 
			 
			//Create dataTable columns
			for (int intCounter = 0; intCounter <= intFieldCount - 1; intCounter++) 
			{ 
				objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter)); 
			} 

			//Insert requested records into the dataTable
			objDataTable.BeginLoadData(); 
			object[] objValues = new object[intFieldCount - 1]; 
			int iCount = 0;
			while (reader.Read()) 
			{ 
				iCount++;
				if ((iCount >= startPossition) && (iCount <= endPossition)){
				reader.GetValues(objValues); 
				objDataTable.LoadDataRow(objValues, true); 
				}
			} 
			reader.Close(); 
			objDataTable.EndLoadData(); 
			ViewState["TotalSize"] = iCount;
			return objDataTable; 
		}

		public string GetProductImage(string Image) 
		{ 
			//Build image link (for dynamic thumbnail
			if ((Image != "")) 
			{ 
				return "<IMG src=\"MakeThumb.aspx?ID=" + Image + "&W=" + ConfigurationSettings.AppSettings["MaxThumbnailWidth"] + "\" align=\"left\" border=\"0\">"; 
			} 
			else 
			{ 
				return ""; 
			} 
		}

		public void BuildPagersLinks() 
		{ 
			//Clear existing content from tableDefinisions
			tblCountTop.Controls.Clear(); 
			tblCount.Controls.Clear(); 
			
			//Ser local variables
			int iTemp = 0; 
			int iVal = 0; 
			int totalSize = (int)ViewState["TotalSize"];
			int pageSize = Convert.ToInt32(ConfigurationSettings.AppSettings["PageCount"]);
			int categoryID = (Request.QueryString["CategoryID"] != null ? Convert.ToInt32(Request.QueryString["CategoryID"]) : -1);
			int currentPage = Convert.ToInt32(ViewState["CurrentPage"].ToString());
			int scid = (Request.QueryString["scid"] != null ? Convert.ToInt32(Request.QueryString["scid"]) : -1);
			 
			//Create a link for each x (specified) number of recored
			// i.e 1 2 3 4
			for (int i = 0; i <= totalSize; i++) 
			{ 
				iTemp += 1; 
				if ((iTemp == pageSize))
				{ 
					//Set variables and create hyperLinks
					iVal += 1; 
					iTemp = 0; 
					HyperLink btnTop = new HyperLink(); 
					HyperLink btn = new HyperLink(); 
					btn.ID = iVal.ToString(); 
					btn.Text = iVal.ToString(); 
					btn.CssClass = "ProductListItem";
					btnTop.ID = iVal.ToString() + "-Top"; 
					btnTop.Text = iVal.ToString(); 
					btnTop.CssClass = "ProductListItem";
					string clickPath;

					//Create links
					if (categoryID != -1) 
					{ 
						clickPath ="../Default.aspx?scid=" + scid + "&CategoryID=" + categoryID + "&selection=" + Request.QueryString["selection"] + "&PageNumber=" + iVal + (Request.Params["txtSearch"] != null ? "&txtSearch=" + Request.Params["txtSearch"].ToString() : ""); 
					} 
					else 
					{ 
						clickPath = "../Default.aspx?scid=" + scid + "&PageNumber=" + iVal + (Request.Params["txtSearch"] != null ? "&txtSearch=" + Request.Params["txtSearch"].ToString() : ""); 
					} 
					btnTop.NavigateUrl = clickPath;
					btn.NavigateUrl = clickPath;

					//Enable or disable the links (current link is always disabled
					if ((btn.ID == currentPage.ToString())) 
					{ 
						btnTop.Enabled = false; 
						btn.Enabled = false; 
					} 

					//Add hyperLinks to the tableDefinitions
					tblCount.Controls.Add(btn); 
					tblCount.Controls.Add(new LiteralControl("&nbsp;&nbsp;")); 
					tblCountTop.Controls.Add(btnTop); 
					tblCountTop.Controls.Add(new LiteralControl("&nbsp;&nbsp;")); 
				} 
			} 

			//This method catches any odd numbered paging (iTemp > 0) & (iTemp != pageSize)
			if (totalSize > (iVal*pageSize))
			{ 
				//Set variables and create hyperLinks
				iVal += 1; 
				iTemp = 0; 
				HyperLink btnTop = new HyperLink(); 
				HyperLink btn = new HyperLink(); 
				btn.ID = iVal.ToString(); 
				btn.Text = iVal.ToString(); 
				btn.CssClass = "ProductListItem";
				btnTop.ID = iVal.ToString() + "-Top"; 
				btnTop.Text = iVal.ToString(); 
				btnTop.CssClass = "ProductListItem";
				string clickPath;

				//Create links
				if (categoryID != -1) 
				{ 
					clickPath = "../Default.aspx?scid=" + scid + "&CategoryID=" + categoryID + "&selection=" + Request.QueryString["selection"] + "&PageNumber=" + iVal + (Request.Params["txtSearch"] != null ? "&txtSearch=" + Request.Params["txtSearch"].ToString() : ""); 
				} 
				else 
				{ 
					clickPath = "../Default.aspx?scid=" + scid + "&PageNumber=" + iVal + (Request.Params["txtSearch"] != null ? "&txtSearch=" + Request.Params["txtSearch"].ToString() : ""); 
				} 
				btnTop.NavigateUrl = clickPath;
				btn.NavigateUrl = clickPath;

				//Enable or disable the links (current link is always disabled
				if (btn.ID == currentPage.ToString())
				{ 
					btnTop.Enabled = false; 
					btn.Enabled = false; 
				} 

				//Add hyperLinks to the tableDefinitions
				tblCount.Controls.Add(btn); 
				tblCount.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));  
				tblCountTop.Controls.Add(btnTop); 
				tblCountTop.Controls.Add(new LiteralControl("&nbsp;&nbsp;")); 
			} 

			//Create next previous links
			//i.e. << or >>

			//If the current page is the fist paging number
			//disable link else enable the link
			if ((currentPage - 1) <= 0) 
			{ 
				btnPrevTop.Enabled = false; 
				btnPrev.Enabled = false; 
			} 
			else 
			{ 
				btnPrevTop.Enabled = true;
				btnPrev.Enabled = true; 
				string clickPath;

				//If link is not disables (there are records lower that the current record
				//create the link
				if (categoryID != -1) 
				{ 
					clickPath = "../Default.aspx?scid=" + scid + "&CategoryID=" + categoryID + "&selection=" + Request.QueryString["selection"] + "&PageNumber=" + (currentPage -1) + (Request.Params["txtSearch"] != null ? "&txtSearch=" + Request.Params["txtSearch"].ToString() : ""); 
				} 
				else 
				{ 
					clickPath = "../Default.aspx?scid=" + scid + "&PageNumber=" + (currentPage -1) + (Request.Params["txtSearch"] != null ? "&txtSearch=" + Request.Params["txtSearch"].ToString() : ""); 
				} 
				btnPrevTop.NavigateUrl = clickPath;
				btnPrev.NavigateUrl = clickPath;
			} 

			//If the current page is the last paging number
			//disable link else enable the link
			if ((currentPage * pageSize) >= totalSize)
			{ 
				btnNextTop.Enabled = false; 
				btnNext.Enabled = false; 
			} 
			else 
			{ 
				btnNextTop.Enabled = true; 
				btnNext.Enabled = true; 
				string clickPath;

				//If link is not disables (there are records higher that the current record
				//create the link
				if (categoryID != -1) 
				{ 
					clickPath = "../Default.aspx?scid=" + scid + "&CategoryID=" + categoryID + "&selection=" + Request.QueryString["selection"] + "&PageNumber=" + (currentPage +1) + (Request.Params["txtSearch"] != null ? "&txtSearch=" + Request.Params["txtSearch"].ToString() : ""); 
				} 
				else 
				{ 
					clickPath = "../Default.aspx?scid=" + scid + "&PageNumber=" + (currentPage +1) + (Request.Params["txtSearch"] != null ? "&txtSearch=" + Request.Params["txtSearch"].ToString() : ""); 
				} 
				btnNextTop.NavigateUrl = clickPath;
				btnNext.NavigateUrl = clickPath;
			} 
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion
	}
}
